<?php

namespace App\Http\Controllers\test;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Request;
use SF\libaray\curl;

class index extends Controller
{
    // 服务名称
    protected $system;

    // 服务系统
    protected $service;

    // 服务密钥
    protected $key;

    public function __construct()
    {
        $this->system = Request::route( 'system' );

        $this->service = Request::route( 'service' );

        $this->key = Config::get( 'user.' . $this->system . '_key' );
    }

    // 解密参数
    public function decode_param()
    {
        // 参数
        $content = Request::post( 'content' );

        // 参数解码
        return response()->json( json_decode( base64_decode( $content ), true ) );
    }

    // 加密参数
    public function encode_param()
    {
        $data = Request::post();    // 获取数据

        // 时间戳
        $timestamp = time();

        // 参数
        $content = base64_encode( json_encode( $data ) );
        
        ksort( $data ); // 数据进行ascii码排序
        $data = http_build_query( $data ); // 数据转url
        $signature = strtolower( md5( $this->service . $this->key . $data . $timestamp ) ); // 加密数据
        return response()->json( [ 'service' => $this->service, 'content' => $content, 'timestamp' => $timestamp, 'signature' => $signature ] );
    }

    // 模拟发送数据
    public function send()
    {
        $data = Request::post();    // 获取数据

        // 时间戳
        $timestamp = time();

        // 参数
        $content = base64_encode( json_encode( $data ) );
        
        ksort( $data ); // 数据进行ascii码排序
        $data = http_build_query( $data ); // 数据转url
        $signature = strtolower( md5( $this->service . $this->key . $data . $timestamp ) ); // 加密数据
        $params = [ 'service' => $this->service, 'content' => $content, 'timestamp' => $timestamp, 'signature' => $signature ];
        
        // 模拟发送数据
        $curl = new curl();    //curl
        
        // 发送数据
        $response = $curl->post( Request::root() . '/' . $this->system, $params );
        return $response;
    }

    // 模式执行
    public function run()
    {

    }
}